const express = require('express')
const app = express()
const request = require('request')

app.use(express.static('static'))

// 136 148

let urls = [
  {
    url: 'http://api.rongsue.com',
    level: 9
  },
  {
    url: 'http://192.168.1.148:8088',
    level: 5
  },
  {
    url: 'http://192.168.1.136:8088',
    level: 7
  },
  {
    url: 'http://127.0.0.1:8088',
    level: 3
  }
]

let proxyObj = null
let can_connect = false

for (let item of urls) {
  request.head(item.url, function (err) {
    if (err) {
      console.log(item.url, " can't connect")
    } else {
      if (!proxyObj) {
        proxyObj = item
        can_connect = true
        console.log('connect ', proxyObj.url)
      } else {
        if (item.level > proxyObj.level) {
          proxyObj = item
          can_connect = true
          console.log('reconnect ', proxyObj.url)
        } else {
          console.log(
            item.url,
            " can connect,but it's level is low,so we don't connect it"
          )
        }
      }
    }
  })
}

app.all('*', function (req, res, next) {
  if (can_connect) {
    req.pipe(request(proxyObj.url + req.url)).pipe(res)
  } else {
    next()
  }
})

let server = app.listen(3033, function () {
  let address = server.address()

  console.log(`http://localhost:${address.port}`)
})
